var HCRM_ACCESS = -1; // -1：异常 0：正常使用 5：初次购买 10：再次购买
var WN_MENU_PANEL = (function() {
	
	/**
	 * make the service menu
	 */
	function makeOneServiceMenu(menus) {
		var e = '';
		$(menus).each(function(idx, first) {
			e += '<li role="presentation" style="margin-left: 0px;" class="';
				if (idx == 0) {
					e += 'active';
				}
				if (!first.available) {
					e += ' unavailable2';
				}
				if (first.childrens && first.childrens.length) {
					e += ' dropdown';
				}
				e += '"';
				// 有二级菜单时，不生成data-url
				if (!first.childrens || !first.childrens.length) {
					e += ' data-url="' + first.url + '"';
					e += ' data-workflowtype="' + first.workFlowType + '"';
				}
			e += '">';
				if (first.childrens && first.childrens.length) { // 有二级菜单
					e += '<a role="button" class="dropdown-toggle" data-toggle="dropdown">+ ' + first.name + '</a>';
					e += '<ul class="dropdown-menu">';
					$.each(first.childrens, function(idx2, second) {
						e += '<li class="' + (second.available?'':'unavailable2') + '"';
							if (second.available) {
								e += ' data-url="' + second.url + '"';
								e += ' data-workflowtype="' + second.workFlowType + '"';
							}
						e += '>';
							e += '<a href="javascript:void(0);">' + second.name + '</a>';
						e += '</li>';
					});
					e += '</ul>';
				} else {
					e += '<a href="javascript:void(0);">' + first.name + '</a>';
				}
			e += '</li>';
		});
		
		var $serviceMenus = $('ul#service-menu-body').append(e);
		$serviceMenus.find('li[data-url]').on('click', function(e) {
			var $that = $(this);
			if (!$that.hasClass('unavailable2')) {
				var url = $that.data('url');
				var $serviceMenu = $('ul#service-menu');
				WeKnow.submit(
					'main.do',
					{
						initPageUrl: $that.data('url'),
						workFlowType: $that.data('workflowtype'),
						initPageTitle: $serviceMenu.data('username'),
						srvUserUUID: $serviceMenu.data('useruuid')
					}
				);
			} else {
				e.stopPropagation();
			}
		});
		
		// 调整top
		$('ul#service-menu').css('top', $('input#user-search-key').css('top'));
	}
	
	/**
	 * make the panel menu
	 */
	function makeMenu() {
		$.post(
			'wncrm_panel_main.do/load',
			null,
			function(data, status) {
				if (data.errcode == 0) {
					var e;

					// 左边panel菜单
					var leftMenus = data.leftMenus;
					if (leftMenus && leftMenus.length) {
						e = '';
						$(leftMenus).each(function(idx, menu) {
							e += '<div class="col-md-4 col-sm-6 col-xs-12 text-center menublock ' + (menu.available ? "" : "unavailable2") + '"';
								e += ' data-menuurl="' + menu.url + '"';
								e += ' data-menutype="' + menu.menuType + '"';
								e += ' data-menuname="' + menu.name + '"';
								if (menu.menuType == 2) {
									e += ' data-workflowtype="' + menu.workFlowType + '"';
								}
							e += '>';
								e += '<img class="icon" src="' + menu.icon1 + '" alt="icon">';
								e += '<p class="name">';
									e += menu.name;
								e += '</p>';
							e += '</div>';
						});
						$('div#left-menus').append(e)
					}
					
					// 右边panel菜单
					var rightMenus = data.rightMenus;
					if (rightMenus && rightMenus.length) {
						e = '';
						$(rightMenus).each(function(idx, menu) {
							e += '<div class="col-md-4 col-sm-6 col-xs-12 text-center menublock ' + (menu.available ? "" : "unavailable2") + '"';
								e += ' data-menuurl="' + menu.url + '"';
								e += ' data-menutype="' + menu.menuType + '"';
								e += ' data-menuname="' + menu.name + '"';
								if (menu.menuType == 2) {
									e += ' data-workflowtype="' + menu.workFlowType + '"';
								}
							e += '>';
								e += '<img class="icon" src="' + menu.icon1 + '" alt="icon">';
								e += '<p class="name">';
									e += menu.name;
								e += '</p>';
							e += '</div>';
						});
						$('div#right-menus').append(e)
					}
					
					// 水平的服务菜单
					var horizonatalMenus = data.horizonatalMenus;
					if (horizonatalMenus && horizonatalMenus.length) {
						makeOneServiceMenu(horizonatalMenus);
					}
					
					HCRM_ACCESS = data.hcrmaccess;
				}
			}
		);
	}
	
	/**
	 * 选择用户
	 */
	function chooseOneUser(user) {
		$('input#user-search-key').val('');
		var $serviceMenu = $('ul#service-menu');
		$serviceMenu.find('label.user-info').html(
			(function(_user) {
				var userTxt = '';
				userTxt += _user.name;
				if (_user.memberId) {
					userTxt +=  '&nbsp;&nbsp;&nbsp;&nbsp;[' + _user.memberId + '] '
				}
				if (user.gender == 1) {
					userTxt += '&nbsp;&nbsp;&nbsp;&nbsp;男';
				} else if (user.gender == 2) {
					userTxt += '&nbsp;&nbsp;&nbsp;&nbsp;女';
				}
				if (user.age != null) {
					userTxt += '&nbsp;&nbsp;&nbsp;&nbsp;' + user.age + '岁';
				} else if (user.birthday != null && WN_AGE_UTIL) {
					userTxt += '&nbsp;&nbsp;&nbsp;&nbsp;' + WN_AGE_UTIL.exchangeAge(user.birthday.format("yyyy-MM-dd"));
				}
				if (_user.phone) {
					userTxt += '&nbsp;&nbsp;&nbsp;&nbsp;' + _user.phone;
				}
				return userTxt;
			})(user)
		);
		$serviceMenu.data('useruuid', user.userUUID).data('username', user.name).show();
		$('body').one('click', function() {
			$serviceMenu.find('button.close').click();
		});
	}
	
	return {
		makeMenu: makeMenu,
		chooseOneUser: chooseOneUser
	}
})();

$(document).ready(function() {
	
	// 生成菜单
	WN_MENU_PANEL.makeMenu();
	
	// 退出并返回登录页面
	$("li#logout").on("click", function() {
		WeKnow.submit('logout');
	});
	$("li#modifyPw").on("click", function() {
		WeKnow.submit(
			'main.do',
			{
				initPageUrl: 'wncrm_pwd_manage.do',
				initPageTitle: '修改密码'
			}
		);
	});
	
	// 点击panel菜单
	$('div#left-menus, div#right-menus').on('click', 'div.menublock', function() {
		var $that = $(this);
		var menuurl = $that.data('menuurl');
		var menutype = $that.data('menutype');
		var menuname= $that.data('menuname');
		
		if (!$that.hasClass('unavailable2')) {
			// 存在访问连接
			if (menuurl && menuurl.length) {
				if (1 == menutype) { // 纵向菜单，直接进入
					WeKnow.submit('main.do',
						{
							initPageUrl: menuurl,
							initPageTitle: menuname
						}
					);
				} else if (2 == menutype) { // 横向菜单，需要选择客户
					var workFlowType = $that.data('workflowtype');
					var $userSearchModal = $('div#userSearchModal');
					$userSearchModal.data('url', menuurl).data('workflowtype', workFlowType).modal('show');
					$userSearchModal.find('.modal-title').text('请选择[' + menuname + ']的对象');
				}
			}
		} else {
			if (HCRM_ACCESS == 5) { // 引导购买
//				WeKnow.newMaxWindow('wncrm_wkaccount_order.do');
				WeKnow.confirm('该功能需要购买才能使用，是否购买？', function() {
					WeKnow.newMaxWindow('wncrm_wkaccount_order.do');
				});
			} else if (HCRM_ACCESS == 10) {
				WeKnow.notifyMsg('账号已过期，请联系客服人员。');
				return false;
			} else {
				return false;
			}
		}
	});
	
	// 客户检索
	var autoSearch = null;
	$('input#user-search-key, input#user-search-key2').on('input', function() { // 按名字检索
		if (autoSearch) clearTimeout(autoSearch);
		
		var $that = $(this);
		$that.next('ul.dropdown-menu.user-dropdown-menu').remove();
		
		var searchKey = $.trim($that.val());
		if (searchKey.length) {
			autoSearch = setTimeout(function() {
				var options = {};
				if (MY_VALIDATOR.isNumber(searchKey)) {
					options.search_phone = searchKey;
				} else {
					options.search_name = searchKey;
				}
				options.result_position = $that;
				if ($that.attr('id') == 'user-search-key') {
					options.result_choose_callback = WN_MENU_PANEL.chooseOneUser;
				} else if ($that.attr('id') == 'user-search-key2') {
					options.result_choose_callback = function(user) {
						var $userSearchModal = $('div#userSearchModal');
						WeKnow.submit(
							'main.do',
							{
								initPageUrl: $userSearchModal.data('url'),
								workFlowType: $userSearchModal.data('workflowtype'),
								initPageTitle: user.name,
								srvUserUUID: user.userUUID
							}
						);
						$userSearchModal.modal('hide');
					};
				}
				options.dropdown_menu_style = 'width: 100%;';
				options.result_norecord_msg = '找到0条数据';
				WN_USER.search(options);
			}, 300);
		} else {
			WN_USER.remove();
		}
	});
	
	// 添加客户
	$('img#useradd, img#useradd2').on('click', function() {
		var options = {};
		options.result_choose_callback = WN_MENU_PANEL.chooseOneUser;
		WN_USER.add(options);
	});
	
	// 给用户选择服务
	var $serviceMenu = $('ul#service-menu');
	$serviceMenu.find('button.close').on('click', function() {
		$serviceMenu.removeData('useruuid').removeData('username').hide();
	});
	
	// 选择服务 后再选择客户
	var $userSearchModal = $('div#userSearchModal');
	$userSearchModal.on('shown.bs.modal', function() {
		$userSearchModal.find('input#user-search-key2').val('');
		$userSearchModal.find('input#user-search-key2').focus();
	}).on('hidden.bs.modal', function() {
		$userSearchModal.removeData('url');
		$userSearchModal.removeData('workflowtype');
	});
});